package com.echo.boot.sync.interview;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA
 * Created By CQ
 * Date: 2020/4/17
 * Time: 0:41
 */
public class T09_00_lock_condition {
    public static void main(String[] args) {
        char[] aI = "ABCDEFG".toCharArray();
        char[] aC = "1234567".toCharArray();
        ReentrantLock lock = new ReentrantLock();
        // 申请2个队列
        // 问题:synchronzied 是同一队列
        // 在 多个生产者和消费者的情况下
        // 多个线程在队列中等待唤醒 有可能唤醒的是 消费者线程
        // notify() 唤醒的可能是消费者线程 所有必须 notifyAll()
        // 这就造成资源浪费.
        // 所以类似 synchronized 的 condition
        // 创建2个队列，一个生产队列(t1).一个消费队列(t2)
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();

        new Thread(() -> {
            lock.lock();
            try {
                for (char c : aI) {
                    System.out.println(c);
                    condition2.signal();
                    condition1.await();
                }
                condition2.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t1").start();


        new Thread(() -> {
            lock.lock();
            try {
                for (char c : aC) {
                    System.out.println(c);
                    condition1.signal();
                    condition2.await();
                }
                condition1.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }, "t2").start();

    }
}
